package cc.comac.mom.datahandlers.entity.config;

import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.bean.config.EquipConnectConfigBean;
import cc.comac.mom.bean.config.EquipConnectConfigGroupBean;
import cc.comac.mom.bean.config.EquipConnectConfigParamBean;
import cc.comac.mom.bean.config.EquipDataConfigParamBean;
import cc.comac.mom.dao.entity.config.EquipConnectConfigDao;
import cc.comac.mom.dao.entity.config.EquipDataConfigDao;
import cc.comac.mom.entity.EquipDevEntity;
import cc.comac.mom.entity.config.EquipConnectConfigEntity;
import cc.comac.mom.entity.config.EquipConnectConfigGroupDetailEntity;
import cc.comac.mom.entity.config.EquipDataConfigEntity;
import cc.comac.mom.entity.config.EquipLabelConfigEntity;
import cc.comac.mom.redis.subscribe.MomEquipRedisChannel;
import cc.comac.mom.redis.subscribe.SubscribeMessage;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.ResultBean;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
@Transactional
public class EquipConnectConfigDataHandler extends ServiceImpl<EquipConnectConfigDao, EquipConnectConfigEntity> {
	@Autowired
	private EquipConnectConfigDao equipConnectConfigDao;
	@Autowired
	private EquipDataConfigDao equipDataConfigDao;

	@Autowired
	private EquipConnectConfigGroupDataHandler equipConnectConfigGroupDataHandler;
	@Autowired
	private EquipConnectConfigGroupDetailDataHandler equipConnectConfigGroupDetailDataHandler;
	@Autowired
	private EquipLabelConfigDataHandler equipLabelConfigDataHandler;
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public ResultBean saveConnectConfig(EquipConnectConfigBean obj) {
		ResultBean resultBean = new ResultBean(true);
		//设置主表数据
		EquipConnectConfigEntity entity=new EquipConnectConfigEntity();
		entity.setDataId(obj.getDataId());
		entity.setDriver(obj.getDriver());
		entity.setPhysicalMedia(obj.getPhysicalMedia());
		if(obj.getGroupList()!=null&&obj.getGroupList().size()>0){
			for(EquipConnectConfigGroupBean e1:obj.getGroupList()){
				if(e1.getDetailList()!=null&&e1.getDetailList().size()>0){
					for(EquipConnectConfigGroupDetailEntity e2:e1.getDetailList()){
						if("connectName".equals(e2.getParamItemKey())){
							entity.setConnectName(e2.getParamItemValue());
						}
						if("connectDesc".equals(e2.getParamItemKey())){
							entity.setRemark(e2.getParamItemValue());
						}
						if("connectIp".equals(e2.getParamItemKey())){
							entity.setIp(e2.getParamItemValue());
						}
						if("samplingPeriod".equals(e2.getParamItemKey())){
							entity.setSamplingPeriod(e2.getParamItemValue());
						}
						if("port".equals(e2.getParamItemKey())){
							entity.setPort(e2.getParamItemValue());
						}
					}
				}
			}
		}
		// 校验主数据重复性
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("connect_name", entity.getConnectName());
		//map.put("data_id",obj.getDataId());
		map.put("row_status", 1);
		List<EquipConnectConfigEntity> selectByMap = equipConnectConfigDao.selectByMap(map);
		if (selectByMap.size() > 0) {
			throw new RuntimeException("连接名" + entity.getConnectName() + "已经存在");
		}

		//保存主连接信息
		baseEntityDataUtil.setBaseEntityData(entity);
		int insert = equipConnectConfigDao.insert(entity);
		if (insert < 1) {
			throw new RuntimeException("新增失败");
		}
		obj.setId(entity.getId());
		//保存驱动对应的属性组信息
		equipConnectConfigGroupDataHandler.saveEquipConnectConfigGroup(entity.getId(),obj.getGroupList());
		resultBean.setObject(obj);
		this.convertAndSend(MomEquipRedisChannel.EQUIP_INFO_CHANNEL_ADD,obj);
	    return resultBean;
	}
	public ResultBean updateConnectConfig(EquipConnectConfigBean obj) {
		ResultBean resultBean = new ResultBean(true);
		//设置主表数据
		if(obj.getGroupList()!=null&&obj.getGroupList().size()>0){
			for(EquipConnectConfigGroupBean e1:obj.getGroupList()){
				if(e1.getDetailList()!=null&&e1.getDetailList().size()>0){
					for(EquipConnectConfigGroupDetailEntity e2:e1.getDetailList()){
						if("connectName".equals(e2.getParamItemKey())){
							obj.setConnectName(e2.getParamItemValue());
						}
						if("connectDesc".equals(e2.getParamItemKey())){
							obj.setRemark(e2.getParamItemValue());
						}
						if("connectIp".equals(e2.getParamItemKey())){
							obj.setIp(e2.getParamItemValue());
						}
						if("samplingPeriod".equals(e2.getParamItemKey())){
							obj.setSamplingPeriod(e2.getParamItemValue());
						}
						if("port".equals(e2.getParamItemKey())){
							obj.setPort(e2.getParamItemValue());
						}
					}
				}
			}
		}
		EquipConnectConfigEntity bean = equipConnectConfigDao.selectById(obj.getId());
		if (bean == null) {
			throw new RuntimeException("修改的数据不存在！");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("connect_name", obj.getConnectName());
		//map.put("data_id",obj.getDataId());
		map.put("row_status", 1);
		List<EquipConnectConfigEntity> selectByMap = equipConnectConfigDao.selectByMap(map);
		if (selectByMap.size() > 0) {
			for (EquipConnectConfigEntity e : selectByMap) {
				if (obj.getId() != e.getId()) {
					throw new RuntimeException("连接名" + obj.getConnectName() + "已经存在");
				}
			}
		}
		baseEntityDataUtil.updateBaseEntityData(obj);
		int update = equipConnectConfigDao.updateById(obj);
		if (update < 1) {
			throw new RuntimeException("修改失败");
		}
		//保存驱动对应的属性组信息
		equipConnectConfigGroupDataHandler.saveEquipConnectConfigGroup(obj.getId(),obj.getGroupList());
		this.convertAndSend(MomEquipRedisChannel.EQUIP_INFO_CHANNEL_UPDATE,obj);
		return resultBean;
	}

	public ResultBean delete(EquipConnectConfigEntity obj) {
		ResultBean resultBean = new ResultBean(true);
		if (obj == null) {
			throw new RuntimeException("数据为空");
		}
		EquipConnectConfigEntity equipDevEntity = equipConnectConfigDao.selectById(obj.getId());
		if (equipDevEntity == null) {
			throw new RuntimeException("删除的数据不存在！");
		}
		equipDevEntity.setRowStatus(0);
		int updateById = equipConnectConfigDao.updateById(equipDevEntity);
		if (updateById < 1) {
			throw new RuntimeException("删除失败！");
		}
		obj.setDataId(equipDevEntity.getDataId());
		//删除配置
		equipConnectConfigGroupDataHandler.delete(obj.getId());
		//删除标签
		equipLabelConfigDataHandler.deleteByConnectIds(Arrays.asList(obj.getId()));
        this.convertAndSend(MomEquipRedisChannel.EQUIP_INFO_CHANNEL_DELETE,obj);
		return resultBean;
	}

	public void convertAndSend(String crud,EquipConnectConfigEntity obj){
		EquipDataConfigEntity data=equipDataConfigDao.selectById(obj.getDataId());
		SubscribeMessage subscribeMessage=new SubscribeMessage();
		subscribeMessage.setConnectId(obj.getId());
		subscribeMessage.setDataId(data.getId());
		subscribeMessage.setNewIp(data.getServiceIp());
		subscribeMessage.setCrud(crud);
		stringRedisTemplate.convertAndSend(MomEquipRedisChannel.EQUIP_INFO_CHANNEL,JSONObject.toJSONString(subscribeMessage));

	}

	public ResultBean deleteByDataId(Long dataId) {
		ResultBean resultBean = new ResultBean(true);
		if (dataId == null) {
			throw new RuntimeException("数据为空");
		}
		QueryWrapper<EquipConnectConfigEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("data_id",dataId);
		List<Long> connectIds=new ArrayList<>();
		List<EquipConnectConfigEntity> list = equipConnectConfigDao.selectList(queryWrapper);
		if (list != null&&list.size()>0) {
			for(EquipConnectConfigEntity e:list){
				connectIds.add(e.getId());
				e.setRowStatus(0);
				baseEntityDataUtil.updateBaseEntityData(e);
			}
			this.updateBatchById(list);
		}
		//删除配置
		equipConnectConfigGroupDataHandler.deleteByConnectIds(connectIds);
		//删除标签
		equipLabelConfigDataHandler.deleteByConnectIds(connectIds);
		return resultBean;
	}

	public EquipConnectConfigBean getById(long id) {
		EquipConnectConfigEntity config=equipConnectConfigDao.selectById(id);

		EquipConnectConfigBean bean = new EquipConnectConfigBean();
		bean.setId(config.getId());
		bean.setPhysicalMedia(config.getPhysicalMedia());
		bean.setDriver(config.getPhysicalMedia());
		bean.setDataId(config.getDataId());
		bean.setCreationTime(config.getCreationTime());
		bean.setCreator(config.getCreator());
		bean.setGroupList(equipConnectConfigDao.selectDetailById(id));
		return bean;
	}

	public EquipConnectConfigParamBean selectBySomeFields(EquipConnectConfigParamBean obj) {
		if (obj.getPageNum() == null) {
			obj.setPageNum(1);
		}

		if (obj.getPageSize() == null) {
			obj.setPageSize(10);
		}
		QueryWrapper<EquipConnectConfigEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.orderByDesc("creation_time");
		Page<EquipConnectConfigEntity> page = new Page<>(obj.getPageNum(), obj.getPageSize(), true);
		IPage<EquipConnectConfigEntity> selectPage = equipConnectConfigDao.selectPage(page, queryWrapper);
		obj.setEntityList(selectPage.getRecords());
		obj.setPageCount((int) selectPage.getPages());
		obj.setTotalQuantity((int) selectPage.getTotal());
		return obj;
	}
}
